#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char *argv[])
{
    DIR *dir;
    struct dirent *entry;
    struct stat file_stat;
    int opt_1=0;
    
    int i;
    for(i=1;i<argc;i++)
    {
         if (strcmp(argv[i], "-l")==0) 
         {
             opt_1=1;
          }
    }
    dir=opendir(".");
    if(dir==NULL)
    {
        printf("open directory error");
        return -1;
    }
    while ((entry = readdir(dir)) != NULL)
    {
        char file_path[258];
        snprintf(file_path, sizeof(file_path), "%s/%s", ".", entry->d_name);
        if (stat(file_path, &file_stat) == -1)
        {
              continue;
         }
        if(opt_1)
        {
            char permissions[10];
            snprintf(permissions, sizeof(permissions), "%c%c%c%c%c%c%c%c%c",
                    (file_stat.st_mode & S_IRUSR) ? 'r' : '-',
                    (file_stat.st_mode & S_IWUSR) ? 'w' : '-',
                    (file_stat.st_mode & S_IXUSR) ? 'x' : '-',
                    (file_stat.st_mode & S_IRGRP) ? 'r' : '-',
                    (file_stat.st_mode & S_IWGRP) ? 'w' : '-',
                    (file_stat.st_mode & S_IXGRP) ? 'x' : '-',
                    (file_stat.st_mode & S_IROTH) ? 'r' : '-',
                    (file_stat.st_mode & S_IWOTH) ? 'w' : '-',
                    (file_stat.st_mode & S_IXOTH) ? 'x' : '-');
            printf("%s %s\n", permissions, entry->d_name);
        }
        else
        {
            printf("%s\n", entry->d_name);
        }
    }
    closedir(dir);
    return 0;
}

